﻿using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Views;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace JiveMessenger.ViewModels
{
    public class ViewModelCropEmoticonPage : ViewModelCropImageBase
    {
        private int maxEmoticonWidth=250;
        private int maxEmoticonHeight=100;
        public override RelayCommand SaveCommand { get; set; }
        public ViewModelCropEmoticonPage(IClient currentClient, INavigationService navService)
            : base(currentClient, navService)
        {
            SaveCommand = new RelayCommand(SaveEmoticonCommandAction);
        }

        private async void SaveEmoticonCommandAction()
        {
            ShowProgressOverlay = true;
            string newFileName = "";
            IRandomAccessStream stream = null;
            WriteableBitmap wb = null;// (WriteableBitmap)this.AvatarImageSource;
            try
            {
                if (_croppedData != null)
                {
                    //wb = new WriteableBitmap(AvatarImageSource.PixelWidth, AvatarImageSource.PixelHeight);
                    //await wb.SetSourceAsync(_croppedData);
                    wb = await CropBitmap.CreateWritableBitmap(_croppedData);
                }
                else
                {
                    wb = await CropBitmap.CreateWritableBitmap(OriginalImageFile);
                }

                int resizeWidth = wb.PixelWidth;
                int resizeHeight = wb.PixelHeight;

                if (resizeWidth > maxEmoticonWidth)
                {
                    resizeWidth = maxEmoticonWidth;
                    resizeHeight = (int)Math.Round(((double)wb.PixelHeight * ((double)maxEmoticonWidth/ (double)wb.PixelWidth)));
                }
                if (resizeHeight > maxEmoticonHeight)
                {
                    resizeHeight = maxEmoticonHeight;
                    resizeWidth = (int)Math.Round(((double)wb.PixelWidth * ((double)maxEmoticonHeight / (double)wb.PixelHeight)));
                }

              //  Debug.Assert(Math.Abs((resizeWidth / resizeHeight) - (wb.PixelWidth / wb.PixelHeight))==0);
                wb = wb.Resize(resizeWidth, resizeHeight, WriteableBitmapExtensions.Interpolation.Bilinear);
                stream = await SaveToStream(wb);
                //var bitmap = await CropBitmap.ResizeBitmapAsync(_croppedData, new Size(200, 200));
                //var stream = await SaveToStream(bitmap);
                //  var stream = await CropBitmap.ResizeBitmapAsync(_croppedData, 200, 200);
                byte[] data = await StaticMethods.LoadImageData(stream);
                string md5 = await StaticMethods.ComputeMD5Async(data);
                string ext = Path.GetExtension(OriginalImageFile.Name);
                newFileName = md5 + ext;
                StorageFolder folder = await StaticMethods.GetEmoticonStorageFolderForUser(_currentClient.CurrentUserInfo.UserName);
                //  StorageFile newFile = await folder.CreateFileAsync(newAvatarName, CreationCollisionOption.ReplaceExisting);
                //await CropBitmap.SaveCroppedBitmapAsync(OriginalImageFile, newFile, new Point(CropLeft, CropTop), new Size(CropWidth, CropHeight));
               StorageFile storedEmoticon = await StaticMethods.SaveImageToStorage(folder, data, newFileName, CreationCollisionOption.ReplaceExisting);
                //_currentClient.UserSettings.Avatar = new JmShared.Avatar()
                //{
                //    Extension = ext,
                //    Hash = md5
                //};

                //_currentClient.Connection.SendCommand(_currentClient.UserSettings, JmShared.ClientCommands.WpSettings);
  
                _navigationService.NavigateTo("AddEmoticonPage", new Tuple<bool,StorageFile>(false,storedEmoticon));
                
            }
            finally
            {
                if (stream != null)
                    stream.Dispose();
                ShowProgressOverlay = false;
            }
        }
        public override void Cleanup()
        {
            base.Cleanup();
            SimpleIoc.Default.Unregister<ViewModelCropEmoticonPage>(VmHelper.Locator.ViewModelCropEmoticonPageKey);
            VmHelper.Locator.ViewModelCropEmoticonPageKey = System.Guid.NewGuid().ToString();

        }
    }
}
